﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using WebApplicationFileSys.Filter;
using WebApplicationFileSys.Models;

namespace WebApplicationFileSys.Controllers
{
    public class HomeController : Controller
    {

        [LoginFilter]
        public ActionResult Index(int pageIndex = 1, int pageSize = 20)
        {

            var userList = SF.db.ChatUser;
            PageMode<ChatUser> pager = new PageMode<ChatUser>(pageIndex, pageSize, userList.Count());
            List<ChatUser> List = userList.OrderByDescending(d => d.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            pager.Items = List;

            return View(pager);
        }

        //文件浏览入口
        [LoginFilter]
        public ActionResult FileList()
        {
            string dirNew = Path.Combine(KeyValueConfig.fileSaveDir);
            if (!Directory.Exists(dirNew))
            {
                System.IO.Directory.CreateDirectory(dirNew);
            }
            var list = System.IO.Directory.GetFileSystemEntries(KeyValueConfig.fileSaveDir);
            List<FileInfoMy> listMy = new List<FileInfoMy>();
            foreach (var item in list)
            {
                var createDatetime = System.IO.File.GetCreationTime(item);
                bool isDir = System.IO.Directory.Exists(item);
                var attri = System.IO.File.GetAttributes(item);
                long bytes = 0;
                string fileSize = string.Empty;
                if (isDir)
                {
                }
                else //if (attri == FileAttributes.Normal)
                {
                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(item);
                    bytes = fileInfo.Length;

                    decimal kb = Math.Round((decimal)bytes / (decimal)1024, 2);
                    if (kb < 1024)
                    {
                        fileSize = kb + " KB";
                        goto Calc_file_size;
                    }
                    decimal mb = Math.Round((decimal)kb / (decimal)1024, 2);
                    if (mb < 1024)
                    {
                        fileSize = mb + " MB";
                        goto Calc_file_size;
                    }
                    decimal GB = Math.Round((decimal)mb / (decimal)1024, 2);
                    fileSize = GB + " GB";
                }
                Calc_file_size:
                FileInfoMy info = new FileInfoMy();
                info.FileType = attri;
                info.CreateTime = createDatetime;
                info.FileName = Path.GetFileName(item);
                info.FileNamePath = item.Replace(KeyValueConfig.fileSaveDir, "").Replace("\\", "/").TrimStart('/');
                info.FileSize = fileSize;
                listMy.Add(info);
            }
            listMy = listMy.OrderBy(x => x.FileType).ToList();
            ViewBag.listMy = listMy;

            return View();
        }
        //文件浏览入口
        [LoginFilter]
        public ActionResult GetFileList()
        {
            //var gggg = System.IO.Directory.GetDirectories("D:\\迅雷下载");
            var list = System.IO.Directory.GetFileSystemEntries(KeyValueConfig.fileSaveDir);
            List<FileInfoMy> listMy = new List<FileInfoMy>();
            foreach (var item in list)
            {
                var createDatetime = System.IO.File.GetCreationTime(item);
                bool isDir = System.IO.Directory.Exists(item);
                var attri = System.IO.File.GetAttributes(item);
                long bytes = 0;
                string fileSize = string.Empty;
                if (isDir)
                {
                }
                else //if (attri == FileAttributes.Normal)
                {
                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(item);
                    bytes = fileInfo.Length;

                    decimal kb = Math.Round((decimal)bytes / (decimal)1024, 2);
                    if (kb < 1024)
                    {
                        fileSize = kb + " KB";
                        goto Calc_file_size;
                    }
                    decimal mb = Math.Round((decimal)kb / (decimal)1024, 2);
                    if (mb < 1024)
                    {
                        fileSize = mb + " MB";
                        goto Calc_file_size;
                    }
                    decimal GB = Math.Round((decimal)mb / (decimal)1024, 2);
                    fileSize = GB + " GB";
                }
                Calc_file_size:
                FileInfoMy info = new FileInfoMy();
                info.FileType = attri;
                info.CreateTime = createDatetime;
                info.FileName = Path.GetFileName(item);
                info.FileNamePath = item.Replace(KeyValueConfig.fileSaveDir, "").Replace("\\", "/").TrimStart('/');
                info.FileSize = fileSize;
                listMy.Add(info);
            }
            listMy = listMy.OrderBy(x => x.FileType).ToList();
            ViewBag.listMy = listMy;

            return PartialView("../Home/ModeList");
        }

        //点击查看目录
        [LoginFilter]
        public ActionResult SeeDir(string dirNew, DirType Dir = DirType.View)
        {
            dirNew = dirNew.TrimStart('/');
            ViewBag.dirNew = dirNew;

            string dirInput = Path.Combine(KeyValueConfig.fileSaveDir, dirNew);
            var list = System.IO.Directory.GetFileSystemEntries(dirInput);
            List<FileInfoMy> listMy = new List<FileInfoMy>();
            foreach (var item in list)
            {
                var createDatetime = System.IO.File.GetCreationTime(item);

                //是否为文件夹？
                //var attri = System.IO.File.GetAttributes(item);
                bool isDir = System.IO.Directory.Exists(item);

                long bytes = 0;
                string fileSize = string.Empty;
                if (isDir)
                {
                }
                else //if (attri == FileAttributes.Normal)
                {
                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(item);
                    bytes = fileInfo.Length;

                    decimal kb = Math.Round((decimal)bytes / (decimal)1024, 2);
                    if (kb < 1024)
                    {
                        fileSize = kb + " KB";
                        goto Calc_file_size;
                    }
                    decimal mb = Math.Round((decimal)kb / (decimal)1024, 2);
                    if (mb < 1024)
                    {
                        fileSize = mb + " MB";
                        goto Calc_file_size;
                    }
                    decimal GB = Math.Round((decimal)mb / (decimal)1024, 2);
                    fileSize = GB + " GB";
                }
                Calc_file_size:
                FileInfoMy info = new FileInfoMy();
                info.FileType = System.IO.File.GetAttributes(item);
                info.CreateTime = createDatetime;
                info.FileName = Path.GetFileName(item);
                info.FileNamePath = item.Replace(KeyValueConfig.fileSaveDir, "").Replace("\\", "/");
                info.FileSize = fileSize;
                listMy.Add(info);
            }
            listMy = listMy.OrderBy(x => x.FileType).ToList();
            ViewBag.listMy = listMy;

            switch (Dir)
            {
                case DirType.View:
                    return View("FileList");
                case DirType.PartialView:
                    return PartialView("../Home/ModeList");
                default:
                    return View("FileList");
            }


        }

        //点击下载文件
        [LoginFilter]
        public ActionResult SeeFile(string file)
        {
            string file2 = file.TrimStart('/');
            string filePath = Path.Combine(KeyValueConfig.fileSaveDir, file2);
            string fileDownName = Path.GetFileName(file);
            /*
                application/pdf
                text/xml
                text/html
                text/css
                text/javascript
                text/plain
                video/mp4
             */
            #region 浏览器在线预览文件内容
            string extend = Path.GetExtension(file).ToLower();
            string mime = "application/octet-stream";
            switch (extend)
            {
                case ".jpg":
                case ".jfif":
                case ".gif":
                case ".png":
                case ".bmp":
                case ".ico":
                    mime = "image/jpeg";
                    break;
                case ".pdf":
                    mime = "application/pdf";
                    break;

                case ".xml":
                case ".config":
                    mime = "text/xml";
                    break;


                //case ".html":
                //    mime = "text/html";
                //    break;

                case ".css":
                    mime = "text/css";
                    break;
                case ".js":
                    mime = "text/javascript";
                    break;

                case ".html":
                case ".xaml":
                case ".cs":
                case ".txt":
                case ".ini":
                case ".md":
                    mime = "text/plain";
                    break;
                case ".mp4":
                    mime = "video/mp4";
                    break;
                default:
                    break;
            }
            if (mime.Equals("application/octet-stream"))
            {
                return File(filePath, mime, fileDownName);
            }
            #endregion
            return File(filePath, mime);
        }


        [LoginFilter]
        public ActionResult DelFile(string file)
        {
            string file2 = file.TrimStart('/');
            string filePath = Path.Combine(KeyValueConfig.fileSaveDir, file2);

            try
            {
                if (Directory.Exists(filePath))
                {
                    string[] files = Directory.GetFiles(filePath);
                    if (files.Length == 0)
                    {
                        Directory.Delete(filePath);  // 删除目录                   
                        return Json(new Result("删除成功", 1)); // 返回删除成功的结果
                    }
                    else
                    {
                        return Json(new Result("目录中存在文件，删除失败")); // 目录中存在文件，返回删除失败的结果
                    }
                }
                else if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);// 删除文件                
                    return Json(new Result("删除成功", 1)); // 返回删除成功的结果
                }
                else
                {
                    return Json(new Result("文件或目录不存在")); // 文件或目录不存在，返回删除失败的结果
                }
            }
            catch (Exception ex)
            {
                // 返回删除失败的结果，并将异常信息返回给前端
                return Json(new Result("删除失败：" + ex.Message));
            }
        }

        //在线查看图片
        [LoginFilter]
        public ActionResult SeeImg(string file)
        {
            string file2 = file.TrimStart('/');
            string filePath = Path.Combine(KeyValueConfig.fileSaveDir, file2);
            //在线预览，必须设置为 image/jpeg
            return File(filePath, "image/jpeg");
        }

        //403 ,拒绝访问
        public ActionResult p403()
        {
            return View();
        }

        [LoginFilter]
        public ActionResult UserList()
        {

            IQueryable<Login> list = SF.db.Login;
            if (LoginMode.LV != "1")
            {
                list = list.Where(x => !x.role.Equals("admin"));
            }

            return View(list.ToList());
        }
        [LoginFilter]
        public new ActionResult User()
        {

            List<Login> list = SF.db.Login.Where(d => d.username == LoginMode.username).ToList();
            return View("UserList", list);
        }
        [JwtAuthorization(KeyValueConfig.TokeKey)]
        public ActionResult PutUser(Login mode)
        {
            var users = SF.db.Login.Find(mode.username);
            if (users != null)
            {

                if (!LoginMode.admin)
                {
                    mode.LV = users.LV;

                }
                if (LoginMode.LV != "1")
                {
                    mode.role = users.role;
                }
       
               SF.db.Entry(users).CurrentValues.SetValues(mode);
               
                if (SF.db.SaveChanges() > 0)
                {
                    return Json(new Result("修改成功", 1));
                }
            }

            return Json(new Result("修改失败"));
        }
    }
    public enum DirType
    {
        /// <summary>
        /// 视图
        /// </summary>
        View,
        /// <summary>
        /// 部分视图
        /// </summary>
        PartialView
    }
}